package tk.paulista.dc.model;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.security.access.prepost.PostFilter;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findItemDaRefeicaosByDiaDoDiarioEquals" })
public class ItemDaRefeicao {

	@NotNull
	@Enumerated
	private Refeicao refeicao;

	@NotNull
	@Min(1L)
	private double quantidade;

	@NotNull
	@ManyToOne
	private Porcao porcaoDeAlimento;

	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "M-")
	private Date diaDoDiario;

	private double quantidadeDeCalorias;

	private double quantidadeDeCaloriasDoDia;

	@ManyToOne
	private Usuario usuarioDoItemDaRefeicao;

	public static double getCaloriasDoDiaDoItemDaRefeicaos(Date diaDoDiario,
			Usuario usuarioDoItemDaRefeicao) {
		if (diaDoDiario == null)
			throw new IllegalArgumentException(
					"The diaDoDiario argument is required");
		EntityManager em = ItemDaRefeicao.entityManager();
		TypedQuery<Double> q = em
				.createQuery(
						"SELECT sum(o.quantidadeDeCalorias) FROM ItemDaRefeicao AS o WHERE o.diaDoDiario = :diaDoDiario and o.usuarioDoItemDaRefeicao = :usuarioDoItemDaRefeicao",
						Double.class);
		q.setParameter("diaDoDiario", diaDoDiario);
		q.setParameter("usuarioDoItemDaRefeicao", usuarioDoItemDaRefeicao);
		return q.getSingleResult();
	}

	@PostFilter("filterObject.usuarioDoItemDaRefeicao.nomeDoUsuario == authentication.name")
	public static List<ItemDaRefeicao> findAllItemDaRefeicaos() {
		return entityManager().createQuery("SELECT o FROM ItemDaRefeicao o",
				ItemDaRefeicao.class).getResultList();
	}

	@PostFilter("filterObject.usuarioDoItemDaRefeicao.nomeDoUsuario == authentication.name")
	public static List<ItemDaRefeicao> findItemDaRefeicaoEntries(
			int firstResult, int maxResults) {
		return entityManager()
				.createQuery("SELECT o FROM ItemDaRefeicao o",
						ItemDaRefeicao.class).setFirstResult(firstResult)
				.setMaxResults(maxResults).getResultList();
	}

}
